package com.example.cloud.controller.finance;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cloud.controller.common.BaseController;
import com.example.cloud.model.dto.PayInfo;
import com.example.cloud.model.dto.QueryModel;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.finance.ChargeDetails;
import com.example.cloud.service.finance.ChargeDetailsService;
import com.example.cloud.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by wangtao on 2018/7/31.
 */
@RestController
@RequestMapping("/charge")
public class ChargeDetailsController extends BaseController {

    @Autowired
    private ChargeDetailsService chargeDetailsService;

    @PostMapping("/search")
    public Result search(@RequestBody QueryModel model) {
        Result result = this.singleQuery(model, ChargeDetails.class);
        JSONArray data = (JSONArray)result.getData();
        for (Object o : data) {
            JSONObject json = (JSONObject)o;
            json.put("actualAmount", json.get("totalPrice"));
        }
        return result;
    }

    @PostMapping("/matchDiscount")
    public Result matchDiscount(@RequestBody List<ChargeDetails> records){
        return ResultUtil.success(chargeDetailsService.doMatchDiscount(records));
    }

    @PostMapping("/compute")
    public Result compute(@RequestBody List<ChargeDetails> records){
        BigDecimal payAmount = BigDecimal.ZERO;
        BigDecimal discountAmount = BigDecimal.ZERO;
        BigDecimal actualAmount = BigDecimal.ZERO;
        for (ChargeDetails record : records) {
            if(record.getTotalPrice() != null){
                payAmount = payAmount.add(record.getTotalPrice());
                discountAmount = discountAmount.add(record.getDiscountAmount());
                actualAmount = actualAmount.add(record.getActualAmount());
            }
        }
        PayInfo payInfo = new PayInfo();
        payInfo.setPayAmount(payAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
        payInfo.setDiscountAmount(discountAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
        payInfo.setActualAmount(actualAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
        payInfo.setDeductAmount(BigDecimal.ZERO);
        return ResultUtil.success(payInfo);
    }
}
